// POP3 Email Client Test Harness (Main)
// =====================================
//
// copyright by Peter Huber, Singapore, 2006
// this code is provided as is, bugs are probable, free for any use at own risk, no 
// responsibility accepted. All rights, title and interest in and to the accompanying content retained.  :-)
//
// based on POP3 Client as a C# Class, by Bill Dean, http://www.codeproject.com/csharp/Pop3client.asp 
// based on Retrieve Mail From a POP3 Server Using C#, by Agus Kurniawan, http://www.codeproject.com/csharp/popapp.asp 
// based on Post Office Protocol - Version 3, http://www.ietf.org/rfc/rfc1939.txt

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Mail;
using System.Text;
using Jfc007.WebLib;
using DotNetNuke;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Log.EventLog;
using DotNetNuke.Services.Scheduling;

namespace Jfc007.WebLib.Pop3Client
{
    public class Pop3 : SchedulerClient
    {

        public Pop3(ScheduleHistoryItem scheduleHistoryItem)
            : base()
        {
            this.ScheduleHistoryItem = scheduleHistoryItem;
        }

        public override void DoWork()
        {
            string pos = "0";
            try
            {

                //run indexing events.
                this.Progressing();    //notify scheduler that this task is in progress
                pos = "1";


                // TODO: Remove the comment signs from the next line, if you want to create some sample emails.
                //      SendTestmail();
                //If you get a run time error her: SmtpFailedRecipientException, 'Mailbox unavailable. The server response was: 5.7.1 Unable to relay for',
                //then you need to change the settings of the local IIS/SMTP server.
                EventLogController logController = new EventLogController();

                DotNetNuke.Entities.Portals.PortalController oCtlrP = new DotNetNuke.Entities.Portals.PortalController();
                System.Collections.ArrayList portals = oCtlrP.GetPortals();
                pos = "2";
                foreach (DotNetNuke.Entities.Portals.PortalInfo portal in portals)
                {
                    pos = "PortalId";
                    int portalId = portal.PortalID;
                    pos = "PortalId" + Convert.ToString(portalId);
                    //LogInfo log = new LogInfo("POP3 MIME Client Demo");
                    //logController.AddLog( log );  
                    //log. Console.WriteLine("=====================");
                    //Console.WriteLine();

                    Pop3ServerController pop3ServerController = new Pop3ServerController();
                    Pop3ServerInfo pop3ServerInfo = pop3ServerController.GetPop3Server(portalId);
                    if (pop3ServerInfo != null)
                    {
                        pos = "Pop3ServerInfo" + Convert.ToString(portalId);
                        string password = pop3ServerInfo.Password;
                        string user = pop3ServerInfo.User;
                        Int32 port = Convert.ToInt32(pop3ServerInfo.Port);
                        string server = pop3ServerInfo.ServerName;
                        Boolean useSSL = pop3ServerInfo.UseSsl;


                        //prepare pop client
                        // TODO: Replace server address, username and password with your own credentials.
                        Pop3Client.Pop3MimeClient DemoClient = new Pop3Client.Pop3MimeClient(server, port, useSSL, user, password);
                        //Pop3Client.Pop3MimeClient DemoClient = new Pop3Client.Pop3MimeClient( "pop.gmail.com", 995, true, "JMarques007@gmail.com", "s@xxx@" );
                        pos = "Pop3MimeClient" + Convert.ToString(portalId);
                        //DemoClient.Trace += new TraceHandler(Console.WriteLine);
                        DemoClient.ReadTimeout = 60000; //give pop server 60 seconds to answer

                        //establish connection
                        DemoClient.Connect();

                        //get mailbox stats
                        int numberOfMailsInMailbox, mailboxSize;
                        DemoClient.GetMailboxStats(out numberOfMailsInMailbox, out mailboxSize);

                        //get at most the xx first emails
                        RxMailMessage mm;
                        int downloadNumberOfEmails;
                        int maxDownloadEmails = 5000;
                        if (numberOfMailsInMailbox < maxDownloadEmails)
                        {
                            downloadNumberOfEmails = numberOfMailsInMailbox;
                        }
                        else
                        {
                            downloadNumberOfEmails = maxDownloadEmails;
                        }
                        for (int i = 1; i <= downloadNumberOfEmails; i++)
                        //  for (int i = 243; i >= 0; i--)
                        {

                            DemoClient.GetEmail(i, out mm);
                            //AttachmentCollection col = mm.Attachments;
                            //http://www.codeproject.com/useritems/Pop3MimeClient.asp
                            if (mm.From.Address.ToLower() == "jmarques007@gmail.com")
                            {
                                string ss = string.Empty;
                            }

                            if (mm == null)
                                continue;

                            if (mm.Attachments.Count > 0)
                            {
                                AttachmentCollection col = mm.Attachments;
                                Attachment att = col[0];
                                //
                                //
                                //att.ContentStream.Length




                                if (mm == null)
                                {
                                    //Console.WriteLine( "Email " + i.ToString() + " cannot be displayed." );
                                }
                                else
                                {
                                    //pesquizar o email
                                    DocumentsController controller = new DocumentsController();
                                    MailAddressCollection addressCollection = mm.To;
                                    //Para cada um dos emais a quem foi derigido o email
                                    foreach (MailAddress add in addressCollection)
                                    {

                                        Int32 userId = controller.GetUserIdByUserName(add.Address);
                                        if (userId != Int32.MinValue)
                                        {
                                            if (!(controller.ExistDocumentByEmailId(mm.MessageId)))
                                            {
                                                //novo 
                                                DocumentInfo objDocument = new DocumentInfo();
                                                objDocument.FileName = att.ContentType.Name;
                                                objDocument.Extension = Path.GetExtension(att.ContentType.Name);
                                                //Ir buscar o modulo
                                                objDocument.PortalId =portalId;
                                                //Ir buscar o userId
                                                objDocument.UserId = userId;
                                                objDocument.CreatedByUser = userId;
                                                objDocument.ContentType = att.ContentType.MediaType;
                                                byte[] content = new byte[att.ContentStream.Length];
                                                att.ContentStream.Read(content, 0, content.Length);
                                                objDocument.ByteSize = (int)att.ContentStream.Length;
                                                objDocument.Content = content;
                                                objDocument.FileDescription = mm.Subject;
                                                objDocument.Category = String.Empty;
                                                objDocument.Keywords = "Email upload";
                                                objDocument.Share = false;
                                                objDocument.EmailId = mm.MessageId;
                                                controller.AddDocumentByEmail(objDocument);
                                            }
                                        }
                                    }
                                }
                            }

                        }

                        ////uncomment the following code if you want to write the raw text of the emails to a file.
                        //string myDocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        //string Email;
                        //DemoClient.IsCollectRawEmail = true;
                        //string fileName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Emails From POP3 Server.TXT";
                        //using (StreamWriter sw = File.CreateText(fileName)) {
                        //  for (int i = 1;i <= maxDownloadEmails;i++) {
                        //    sw.WriteLine("Email: " + i.ToString() + "\n===============\n\n");
                        //    DemoClient.GetRawEmail(i, out Email);
                        //    sw.WriteLine(Email);
                        //    sw.WriteLine();
                        //  }
                        //  sw.Close();
                        //}

                        //close connection
                        DemoClient.Disconnect();
                    }
                }

                this.ScheduleHistoryItem.AddLogNote("Read mail Suceeded");
                this.ScheduleHistoryItem.Succeeded = true;
            }
            catch (Exception ex)
            {
                this.ScheduleHistoryItem.Succeeded = false;
                this.ScheduleHistoryItem.AddLogNote("Read mail failed. " + ex.ToString());
                this.Errored(ref ex);
            }

        }



        static void SendMessage(SmtpClient client, MailMessage message)
        {
            client.Send(message);
            //Console.WriteLine("Message '" + message.Subject + "'sent");
            // Clean up.
            message.Dispose();
        }


        /// <summary>
        /// Produce some test emails.
        /// </summary>
        static void SendTestmail()
        {
            SmtpClient client = new SmtpClient("localhost");

            //pure text email
            // TODO: Replace email addresses.
            MailAddress from = new MailAddress("FromName at server.com", "Any name or remove this string");
            MailAddress to = new MailAddress("ToName at server.com", "Any name or remove this string");
            MailMessage message;
            AlternateView thisAlternateView1;
            AlternateView thisAlternateView2;

            //just body text email
            message = new MailMessage(from, to);
            message.Subject = "Text only email";
            message.Body = "This is a test e-mail message with just a plain text body.";
            SendMessage(client, message);

            //pure text email with body and 1 alternative view
            message = new MailMessage(from, to);
            message.Subject = "pure text email with body and 1 alternative view";
            message.Body = "This is the body text";
            thisAlternateView1 = AlternateView.CreateAlternateViewFromString("This is the alternative view text");
            message.AlternateViews.Add(thisAlternateView1);
            SendMessage(client, message);

            //pure text email with no body but 1 alternative view
            message = new MailMessage(from, to);
            message.Subject = "pure text email with no body but 1 alternative view";
            thisAlternateView1 = AlternateView.CreateAlternateViewFromString("This is the alternative view text");
            message.AlternateViews.Add(thisAlternateView1);
            SendMessage(client, message);

            //pure text email with plain text body and 2 alternative views
            message = new MailMessage(from, to);
            message.Subject = "pure text email with plain text body and 2 alternative views";
            message.Body = "This is the body text";
            thisAlternateView1 = AlternateView.CreateAlternateViewFromString("This is the alternative view text");
            message.AlternateViews.Add(thisAlternateView1);
            thisAlternateView2 = AlternateView.CreateAlternateViewFromString("<html><body>This is a <b>HTML<b> text body</body></html>");
            thisAlternateView2.ContentType.MediaType = "text/html";
            message.AlternateViews.Add(thisAlternateView2);
            SendMessage(client, message);

            //email with attachment and UTF8 body encoding
            message = new MailMessage(from, to);
            message.Subject = "email with attachment and UTF8 body encoding";
            message.SubjectEncoding = System.Text.Encoding.ASCII;
            message.Body = "Body text";
            // Include some non-ASCII characters in body and subject.
            string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
            message.Body += Environment.NewLine + someArrows;
            message.BodyEncoding = System.Text.Encoding.UTF8;
            // TODO: Write path and name of an existing file into the following string
            Attachment thisAttachment = new Attachment(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Pic.GIF");
            message.Attachments.Add(thisAttachment);

            message.BodyEncoding = System.Text.Encoding.UTF8;
            message.Subject = "test message 1" + someArrows;
            message.SubjectEncoding = System.Text.Encoding.UTF7;

            client.Send(message);

            //Console.WriteLine("Sending emails completed. Give POP3 server a bit of time to receive the emails, then press 'Return' key.");
            //Console.ReadLine();
        }
    }
}
